/*
 * Copyright (c) 2012 Apple Inc.  All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

#if __OBJC2__

#include "objc-private.h"
#include "DenseMapExtras.h"

// 全局的sel表
static objc::ExplicitInitDenseSet<const char *> namedSelectors;
static SEL search_builtins(const char *key);


/***********************************************************************
* sel_init 初始化全局sel表namedSelectotrs，并注册.cxx_construct和.cxx_destruct
* Initialize selector tables and register selectors used internally.
**********************************************************************/
void sel_init(size_t selrefCount) {
#if SUPPORT_PREOPT
    if (PrintPreopt) {
        _objc_inform("PREOPTIMIZATION: using dyld selector opt");
    }
#endif

    // 让全局的sel表初始化，表里的个数
    namedSelectors.init((unsigned)selrefCount);

    // Register selectors used by libobjc

    mutex_locker_t lock(selLock);

    // 注册c++的构造函数，会放入namedSelectors
    SEL_cxx_construct = sel_registerNameNoLock(".cxx_construct", NO);
    // 注册c++的析构函数，会放入namedSelectors
    SEL_cxx_destruct = sel_registerNameNoLock(".cxx_destruct", NO);
}


static SEL sel_alloc(const char *name, bool copy)
{
    selLock.assertLocked();
    return (SEL)(copy ? strdupIfMutable(name) : name);    
}


const char *sel_getName(SEL sel) 
{
    if (!sel) return "<null selector>";
    return (const char *)(const void*)sel;
}


unsigned long sel_hash(SEL sel)
{
    unsigned long selAddr = (unsigned long)sel;
#if CONFIG_USE_PREOPT_CACHES
    selAddr ^= (selAddr >> 7);
#endif
    return selAddr;
}


BOOL sel_isMapped(SEL sel) 
{
    if (!sel) return NO;

    const char *name = (const char *)(void *)sel;

    if (sel == search_builtins(name)) return YES;

    mutex_locker_t lock(selLock);
    auto it = namedSelectors.get().find(name);
    return it != namedSelectors.get().end() && (SEL)*it == sel;
}

// 判断name是否在dyld3的'必包.selectorTable'中, 有的话，返回对应SEL，没有返回null (我们创建的方法都是可以通过dyld找到的)
static SEL search_builtins(const char *name) {
#if SUPPORT_PREOPT
    /* _dyld_get_objc_selector是在dyld的源码中
     // 是否dyld有唯一的sel Called only by objc to see if dyld has uniqued this selector.
     // Returns the value if dyld has uniqued it, or nullptr if it has not.
     // 这个函数必须是在调用完_dyld_objc_notify_register之后
     // Note, this function must be called after _dyld_objc_notify_register.
     //
     // Exists in Mac OS X 10.15 and later
     // Exists in iOS 13.0 and later
     const char* _dyld_get_objc_selector(const char* selName) {
         // 检查是否在共享缓存表中
         if ( gObjCOpt != nullptr ) {
             if ( const objc_opt::objc_selopt_t* selopt = gObjCOpt->selopt() ) {
                 const char* name = selopt->get(selName);
                 if (name != nullptr)
                     return name;
             }
         }
         if ( gUseDyld3 )
             return dyld3::_dyld_get_objc_selector(selName);
         return nullptr;
     }
     
     // dyld3::必包的selectorTable中是否有这个selName，有的话，返回存储的SEL，没有返回null
     const char* _dyld_get_objc_selector(const char* selName) {
         log_apis("dyld_get_objc_selector()\n");
         return gAllImages.getObjCSelector(selName);
     }
     */
  if (SEL result = (SEL)_dyld_get_objc_selector(name))
    return result;
#endif
    return nil;
}

// 如果name可以通过dyld3.必包.selectorTable来查找到的话, 直接返回SEL; 没有的话，插入到namedSelectors里
static SEL __sel_registerName(const char *name, bool shouldLock, bool copy)  {
    SEL result = 0;

    // 是否加锁
    if (shouldLock) selLock.assertUnlocked();
    else selLock.assertLocked();

    // 判断1：如果传入的name == nil；返回0
    if (!name) return (SEL)0;

    // 判断2：判断name是否在dyld3的'必包.selectorTable'中, 有的话，返回对应SEL，没有返回null
    result = search_builtins(name);
    if (result) return result;          // 通过断点调试：我们创建的类中sel，不在这里，但是系统的类都在这里
    
    // 判断3: 判断是否在namedSelectors里面
    conditional_mutex_locker_t lock(selLock, shouldLock);
	auto it = namedSelectors.get().insert(name);
	if (it.second) {
		// No match. Insert.    里面没有，插入到namedSelectors里(copy==false, 还是返回name）
		*it.first = (const char *)sel_alloc(name, copy);
	}
	return (SEL)*it.first;
}


SEL sel_registerName(const char *name) {
    return __sel_registerName(name, 1, 1);     // YES lock, YES copy
}

// 如果name可以通过dyld3.必包.selectorTable来查找到的话, 直接返回SEL; 没有的话，插入到namedSelectors里，然后返回SEL
SEL sel_registerNameNoLock(const char *name, bool copy) {
    return __sel_registerName(name, 0, copy);  // NO lock, maybe copy
}


// 2001/1/24
// the majority of uses of this function (which used to return NULL if not found)
// did not check for NULL, so, in fact, never return NULL
//
SEL sel_getUid(const char *name) {
    return __sel_registerName(name, 2, 1);  // YES lock, YES copy
}


BOOL sel_isEqual(SEL lhs, SEL rhs)
{
    return bool(lhs == rhs);
}


#endif
